from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from ..models import ClassTaskTodo
from django.http import JsonResponse
from core.models import Notification, StudentClassRelationship
from core.utils import log_operation
import json

def get_tasks(request, classid):
    if request.method == 'GET':
        class_id = int(classid)
        
       #通过日期（strdate）、班级(class_id)和是否处理（is_completed）如果is_completed为false
        tasks=ClassTaskTodo.objects.filter( class_info=class_id, is_completed=False)
        data = [{'id': task.id, 'content': task.content} for task in tasks]
        return JsonResponse({'data': data})
    return JsonResponse({'error': 'Invalid request method'})

class ClassTaskTodoListView(ListView):
    model = ClassTaskTodo
    template_name = 'class_task_todo/list.html'
    context_object_name = 'tasks'
    ordering = ['-start_time']


class ClassTaskTodoDetailView(DetailView):
    model = ClassTaskTodo
    template_name = 'class_task_todo/detail.html'
    context_object_name = 'task'


class ClassTaskTodoCreateView(CreateView):
    model = ClassTaskTodo
    fields = ['class_info', 'start_time', 'end_time', 'content', 'handling_measures']
    template_name = 'class_task_todo/form.html'
    success_url = reverse_lazy('core:task_list')

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.creator = self.request.user
        self.object.save()
        log_operation(
            user=self.request.user,
            operation_type='CREATE',
            content=f'创建了待办事务: {self.object.title}',
            request=self.request
        )
        
        # 自动发送通知给班级所有学生
        student_relationships = StudentClassRelationship.objects.filter(class_id=self.object.class_id)
        for relationship in student_relationships:
            Notification.objects.create(
                title=f'新待办事务: {self.object.title}',
                content=self.object.description,
                sender=self.request.user,
                receiver=relationship.student.user,
                task=self.object
            )
        
        messages.success(self.request, '待办事务创建成功，并已通知班级所有学生！')
        return redirect('core:class_task_todo_list', class_id=self.object.class_id)


class ClassTaskTodoUpdateView(UpdateView):
    def form_valid(self, form):
        response = super().form_valid(form)
        log_operation(
            user=self.request.user,
            operation_type='update',
            content_type='ClassTaskTodo',
            object_id=self.object.id,
            object_name=f'{self.object.content[:50]}',
            request=self.request,
            details=f'更新待办事务: {self.object.content[:50]}'
        )
        return response
    model = ClassTaskTodo
    fields = ['class_info', 'start_time', 'end_time', 'content', 'is_completed', 'handling_measures']
    template_name = 'class_task_todo/form.html'
    success_url = reverse_lazy('core:task_list')


class ClassTaskTodoDeleteView(DeleteView):
    def delete(self, request, *args, **kwargs):
        task = self.get_object()
        log_operation(
            user=request.user,
            operation_type='delete',
            content_type='ClassTaskTodo',
            object_id=task.id,
            object_name=f'{task.content[:50]}',
            request=request,
            details=f'删除待办事务: {task.content[:50]}'
        )
        return super().delete(request, *args, **kwargs)
    model = ClassTaskTodo
    template_name = 'class_task_todo/confirm_delete.html'
    success_url = reverse_lazy('core:task_list')